package com.xzy.rabbit.demo.workqueue.a;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 工作模式（Work Queue）
 *
 * @author xzy
 * @date 2021年9月23日
 */
@Slf4j
@AllArgsConstructor
class Consumer implements Runnable {
    /**
     * TCP连接
     */
    private final Connection connection;
    /**
     * 队列名称
     */
    private final String queueName;

    /**
     * 消费消息
     */
    public void consume() throws IOException {

        // 1.获取信道
        Channel channel = connection.createChannel();

        // 2.接收消息（消费）_自动应答
        String currentThread = Thread.currentThread().getName();
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            log.info(currentThread + " 成功接收：{}\n", new String(message.getBody()));
        };
        CancelCallback cancelCallback = consumerTag -> {
            log.info(currentThread + " 取消接收\nconsumeTag ==> {}\n", consumerTag);
        };
        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
    }

    @Override
    public void run() {
        try {
            consume();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
